package com.xingfly.service;

import com.xingfly.model.Like;
import com.xingfly.repository.LikeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Like服务
 * Created by SuperS on 2016/12/8.
 */
@Service
public class LikeService {
    @Autowired
    private LikeRepository likeRepository;
    @Autowired
    private AccountService accountService;

    /**
     * 创建Like 用户like某个对象
     *
     * @param userId     用户ID
     * @param objectType 对象类型
     * @param objectId   对象ID
     * @return Like对象
     */
    public Like like(Long userId, int objectType, Long objectId) {
        return likeRepository.save(new Like(accountService.find(userId), objectType, objectId));
    }

    /**
     * 解除Like 用户解除like某个对象
     *
     * @param userId     用户ID
     * @param objectType 对象类型
     * @param objectId   对象ID
     */
    public void undoLike(Long userId, int objectType, Long objectId) {
        likeRepository.delete(likeRepository.findByUserIdAndObjectTypeAndObjectId(userId, objectType, objectId));
    }

    /**
     * 判断用户是否喜欢了某个对象
     *
     * @param userId     用户ID
     * @param objectType 对象类型
     * @param objectId   对象ID
     * @return boolean
     */
    public boolean isLike(Long userId, int objectType, Long objectId) {
        boolean result = false;
        if (likeRepository.findByUserIdAndObjectTypeAndObjectId(userId, objectType, objectId) != null) {
            result = true;
        }
        return result;
    }

    /**
     * 获取喜欢某个对象的用户数
     *
     * @param objectType 对象类型
     * @param objectId   对象ID
     * @return long 喜欢的用户数
     */
    public Long likeCount(int objectType, Long objectId) {
        return likeRepository.findLikeUserCount(objectType, objectId);
    }

    /**
     * 返回喜欢某个对象的用户ID列表
     *
     * @param objectType 对象类型
     * @param objectId   对象ID
     * @return List<Long> ID列表
     */
    public List<Long> findLikeUserIds(int objectType, Long objectId) {
        return likeRepository.findLikeUserIds(objectType, objectId);
    }

    /**
     * 获取用户喜欢的数量
     *
     * @param userId 用户ID
     * @return long
     */
    public Long findUserLikeCount(Long userId) {
        return likeRepository.findUserLikeCount(userId);
    }
}
